package com.kmxd.ams.core.excel.convert;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.kmxd.ams.core.common.annotation.ExcelDict;
import com.kmxd.ams.core.util.DictUtil;

import java.lang.reflect.Field;

/**
 * Excel数据字典转换器
 *
 * @author admin
 */
public class ExcelDictConverter implements Converter<String> {

  @Override
  public Class supportJavaTypeKey() {
    return String.class;
  }

  @Override
  public CellDataTypeEnum supportExcelTypeKey() {
    return CellDataTypeEnum.STRING;
  }

  @Override
  public String convertToJavaData(
      ReadCellData cellData,
      ExcelContentProperty excelContentProperty,
      GlobalConfiguration globalConfiguration)
      throws Exception {
    Field field = excelContentProperty.getField();
    String dictCode = AnnotationUtil.getAnnotationValue(field, ExcelDict.class);
    String dictValue = DictUtil.getDictValue(dictCode, cellData.getStringValue());
    return StrUtil.isBlank(dictValue) ? cellData.getStringValue() : dictValue;
  }

  @Override
  public WriteCellData convertToExcelData(
      String s, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration)
      throws Exception {
    Field field = excelContentProperty.getField();
    String dictCode = AnnotationUtil.getAnnotationValue(field, ExcelDict.class);
    String dictLabel = DictUtil.getDictLabel(dictCode, s);
    return new WriteCellData(StrUtil.isBlank(dictLabel) ? s : dictLabel);
  }
}
